package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElaticsearchConfig;
import com.atguigu.gulimall.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author wzq
 * Date      2020/6/2 22:35
 * Describe:
 */
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> upProducts) throws IOException {
        // 保存到es
        //1 建立索引,建立映射关系

        //2，保存数据
        BulkRequest bulkRequest = new BulkRequest();
        upProducts.forEach( item ->{
            // 构建保存请求
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(item.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = client.bulk(bulkRequest, GulimallElaticsearchConfig.COMMON_OPTIONS);

        // 错误处理
        boolean b = bulk.hasFailures();
        return b;
    }
}
